package org.sg20.searchengine.invertedindex;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.sg20.parsename.ParseNameOutputKey;


import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class InvertedIndexDriver {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, URISyntaxException {
        long startTime = System.currentTimeMillis();

        //set up configuration for mapreduce job
        Configuration conf = new Configuration();

        //Parse arguments
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 3) {
            System.err.println("Please input: xxx.jar InvertedIndexDriver [NameListFilePath] [InputPath] [OutputPath].");
            System.exit(1);
        }

        Job job = Job.getInstance(conf, "org.sg20.searchengine.invertedindex.InvertedIndexDriver");

        job.setJarByClass(InvertedIndexDriver.class);
        job.setMapperClass(InvertedIndexMapper.class);
        job.setReducerClass(InvertedIndexReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(ParseNameOutputKey.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        //Distributed cache
        job.addCacheFile(new URI(otherArgs[0]));

        FileInputFormat.addInputPath(job, new Path(otherArgs[1]));
        FileSystem fs = FileSystem.get(conf);

        String outpath = otherArgs[2] + "IndexInverted";
        if (fs.exists(new Path(outpath)))
            fs.delete(new Path(outpath), true);
        FileOutputFormat.setOutputPath(job, new Path(outpath));

        boolean status = job.waitForCompletion(true);

        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");

        System.exit(status ? 0 : 1);
    }
}
